<template>
  <a-modal
    :open="open"
    width="640px"
    :title="rowData?.itemCode ? '修改服务项目' : '新增服务项目'"
    centered
    :ok-button-props="{ disabled: !isCompleted }"
    ok-text="保存"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form class="form-style-flex" name="validate_other" :model="formState">
      <a-form-item label="服务项目" class="w-full" v-bind="validateInfos.itemName">
        <a-input v-model:value="formState.itemName" placeholder="服务项目" @blur="onChangeEmpName" />
      </a-form-item>
      <a-form-item label="助记码" class="w-1/2">
        <a-input v-model:value="formState.zjm" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="时长" class="w-1/2" v-bind="validateInfos.duration">
        <a-input v-model:value="formState.duration" placeholder="请输入" suffix="分钟" />
      </a-form-item>
      <a-form-item label="单位" class="w-1/2" v-bind="validateInfos.dw">
        <a-input v-model:value="formState.dw" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="顺序号" class="w-1/2" v-bind="validateInfos.outorder">
        <a-input v-model:value="formState.outorder" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="备注" class="w-full mb-3">
        <a-textarea v-model:value="formState.memo" :rows="2" placeholder="请输入" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'

const emit = defineEmits(['update:open', 'success'])

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  },
  title: {
    type: String,
    default: ''
  }
})

const formState = ref({
  itemName: '',
  zjm: '',
  duration: '',
  dw: '',
  outorder: '',
  memo: '',
  itemCode: ''
})
const rulesState = ref({
  itemName: [{ required: true, message: '请输入服务项目' }],
  duration: [{ required: true, message: '请输入时长' }],
  dw: [{ required: true, message: '请输入单位' }],
  outorder: [{ required: true, message: '请输入顺序号' }]
})
const { isCompleted, resetFields, validate, validateInfos } = useForm(formState, rulesState)
watch(
  () => props.open,
  (val) => {
    if (val) {
      if (props.rowData?.itemCode) {
        formState.value = { ...props.rowData }
      }
    }
  }
)
const onChangeEmpName = async (e) => {
  const { data, code, msg } = await post('/common/util/getPinyin', {
    name: e.target.value
  })
  if (code !== 0) return message.error(msg)
  formState.value.zjm = data
}

const onOk = async () => {
  await validate()
  const res = await post('/course/courseServiceItem/doSaveServiceItem', formState.value)
  if (res.code === 0) {
    message.success(res.msg)

    emit('success')
    onCancel()
  } else {
    message.error(res.msg)
  }
}

const onCancel = () => {
  emit('update:open', false)
  resetFields()
}
</script>
<style lang="less" scoped></style>
